import merge from "lodash.merge";

// TODO xhr 改为 axios
export const quillRedefine = (config) => {
  const { uploadConfig, ...cfg } = config;

  // 重写图片上传事件, 任何工具按钮的功能都可以重写，默认只重写图片上传事件
  // 合并用户自定义的事件
  const image = function image() {
    const self = this;
    let fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      // 设置图片参数名
      if (uploadConfig.name) {
        fileInput.setAttribute("name", uploadConfig.name);
      }
      // 可设置上传图片的格式
      fileInput.setAttribute("accept", uploadConfig.accept);
      fileInput.classList.add("ql-image");
      // 监听选择文件
      fileInput.addEventListener("change", function () {
        if (!uploadConfig.action) {
          console.error("未配置action(文件上传路径)");
          return;
        }
        // 如果图片限制大小
        if (uploadConfig.size && fileInput.files[0].size >= uploadConfig.size * 1024) {
          fileInput.value = "";
          return;
        }
        // 创建formData
        const formData = new FormData();
        formData.append(uploadConfig.name, fileInput.files[0]);
        // 图片上传
        const xhr = new XMLHttpRequest();
        xhr.open(uploadConfig.methods, uploadConfig.action, true);
        // 如果需要header且存在token
        if (uploadConfig.headers) {
          Object.keys(uploadConfig.headers).forEach(key => {
            xhr.setRequestHeader(key, uploadConfig.headers[key]);
          });
        }
        // 上传数据成功，会触发
        xhr.onload = function () {
          if (xhr.status === 200) {
            const res = JSON.parse(xhr.responseText);
            let url = uploadConfig.res(res);
            if (url) {
              let length = self.quill.getSelection(true).index;
              self.quill.insertEmbed(length, "image", url);
              self.quill.setSelection(length + 1);
              if (uploadConfig.success) {
                uploadConfig.success();
              }
            }
          }
          fileInput.value = "";
        };
        // 开始上传数据
        xhr.upload.onloadstart = function () {
          fileInput.value = "";
          if (uploadConfig.start) {
            uploadConfig.start();
          }
        };
        // 当发生网络异常的时候会触发，如果上传数据的过程还未结束
        xhr.upload.onerror = function () {
          if (uploadConfig.error) {
            uploadConfig.error();
          }
        };
        // 上传数据完成（成功或者失败）时会触发
        xhr.upload.onloadend = function () {
          if (uploadConfig.end) {
            uploadConfig.end();
          }
        };
        xhr.send(formData);
      });
      this.container.appendChild(fileInput);
    }
    fileInput.click();
  };

  // 全部配置
  return merge(cfg, {
    modules: {
      toolbar: {
        handlers: { image }
      }
    }
  });
};

